﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace JumpNFight.Simulation
{
    struct Capsule2d
    {
        Ray Ray;
        float Radius;
        float m_length;
        BoundingSphere m_bsBegin;
        BoundingSphere m_bsEnd;
        BoundingBox m_innerBBox;
        public bool IsFlat
        {
            get
            {
                return Radius == 0;
            }
        }
        public Capsule2d(Ray r, float length, float radius)
        {
#if DEBUG
            if ( radius > 0 )
                System.Diagnostics.Debug.Assert((r.Direction.X != 0 && r.Direction.Y != 0) == false, "Non axis-aligned capsule are not supported");
#endif
            Ray = r;
            m_length = length;
            Radius = radius;

            // start & end boundingspheres
            m_bsBegin = new BoundingSphere(r.Position, radius);
            m_bsEnd = new BoundingSphere(r.Position + length * r.Direction, radius);
            // X-axis
            if (r.Direction.Y == 0)
                m_innerBBox = new BoundingBox(new Vector3(r.Position.X, r.Position.Y - radius, 0), new Vector3(r.Position.X + length * r.Direction.X, r.Position.Y + radius, 0));
            else
                m_innerBBox = new BoundingBox(new Vector3(r.Position.X - radius, r.Position.Y, 0), new Vector3(r.Position.X + radius, r.Position.Y + length * r.Direction.Y, 0));
        }

        /// <summary>
        /// Checks whether the Capsule intersects a specified BoundingBox.
        /// </summary>
        /// <param name="box">The BoundingBox to check for intersection with the Ray.</param>
        /// <returns></returns>
        public bool Intersects(BoundingBox box)
        {
            // simple ray/box intersection
            if (IsFlat)
                return this.Ray.Intersects(box) <= m_length;

            return
                m_bsBegin.Intersects(box) ||
                m_bsEnd.Intersects(box) ||
                m_innerBBox.Intersects(box);
        }

    }
}
